import React from 'react';
import notification from '@kuiper-components/notification';
import cn from 'classnames';
import PropTypes from 'prop-types';
import s from './style.module.css';

export default function DownOnce({ dome, record, className, fileName }) {
	const [timer, setTimer] = React.useState(false);
	const text = fileName || `[${record.note}]ScanV安全监测报告.docx`;
	const downWord = () => {
		if (timer) return;
		setTimer(true);
		return fetch(`/api/v2/report/one_task/download?task_id=${record._id}`)
			.then(res => {
				if (res.ok) {
					return res.blob();
				}
			})
			.then(blob => {
				const url = (window.webkitURL || window.URL).createObjectURL(blob);
				const a = document.createElement('a');
				a.href = url;
				a.download = text;
				a.click();
				setTimer(false);
			})
			.catch(() => {
				notification.error({
					message: `导出${text}`,
					placement: 'top',
					style: { width: '25rem' },
				});
				setTimer(false);
			});
	};

	return (
		<>
			{dome || (
				<div className={cn(className, s.btn)} onClick={() => downWord()}>
					导出报告
				</div>
			)}
		</>
	);
}
DownOnce.propTypes = {
	className: PropTypes.string,
	fileName: PropTypes.string,
	dome: PropTypes.string,
	record: PropTypes.any,
};

DownOnce.defaultProps = {
	className: '',
	record: {},
};
